const errors = require('../errors')
const TokenUtil = require('../util/baseUtil/SecretUtil')
const ObjectUtil = require('../util/baseUtil/ObjectUtil')
const crypto = require('crypto')

/**
 *
 * @param req
 * @param res
 * @param next
 * 认证用户是否登录
 */
module.exports = function(req, res, next) {
    try {
        /**
         *
         * 动态决定是是否需要登录认证
         *
         */

        var test = process.env.NODE_ENV
            // test = 'blah'
            // console.log(test,'sdjsjdjdsj')
            // console.log(req.session.user,'skkdsk')
        if (test === 'production' || test === 'test' || true) {
            //认证用户是否登录
            let user = req.session.user
                // console.log(req.session)
                //请求数据
                // console.log(req.)
                // console.log(user ==undefined,'bosd')
                // let data = ObjectUtil.objectSort(req.body);
                // user = undefined
            if (!user) {
                return next(new errors.UnauthorizedError('用户尚未登录'))
            }

            next()
                // let timestamp = parseInt(req.get('timestamp'));
                // let nonce = parseInt(req.get('nonce'))
                // let signature = req.get('signature');

            // if (!timestamp || !nonce || !signature) {
            //     return next(new errors.ValidationError("缺少必要的参数"))
            // }
            // if (Date.now() - timestamp < -5000) {
            //     return next(new errors.UnauthorizedError('非法请求'))
            // }
            // if (Date.now() - timestamp > 10000) {
            //     return next(new errors.UnauthorizedError('请求超时'))
            // }
            // let token = JSON.parse(TokenUtil.getDecryptAccessToken(user.token));
            // if (token.expire_time - Date.now() < 10000) {
            //     return next(new errors.UnauthorizedError('token失效,请重新登录'))
            // }
            // let obj = ObjectUtil.objectSort({
            //     timestamp,
            //     nonce,
            //     token: req.session.user.token,
            //     data,
            // });
            // let hash = crypto.createHash('md5');
            // hash.update(JSON.stringify(obj));
            // let signature_req = hash.digest('hex');
            // if (signature !== signature_req) {
            //     return next(new errors.UnauthorizedError('验签错误'))
            // }

        } else {
            next()
        }
    } catch (e) {
        next(e)
    }
};